package com.jpush.agent;


import com.jpush.adapter.EnhancerAdapter;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;

public class Agent {
    public static void premain(String agentArgs, Instrumentation inst){
        inst.addTransformer(new ClassFileTransformer() {
            @Override
            public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
                                    ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
                if ("com/jpush/pojo/Person".equals(className)){
                    System.out.println("transform...");
                    ClassReader reader = new ClassReader(classfileBuffer);
                    ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_MAXS);
                    ClassVisitor cv = new EnhancerAdapter(writer);
                    reader.accept(cv,0);


                    // 这里可以不写
//                    try(FileOutputStream fos =
//                                new FileOutputStream("/Users/liyh/dev/GitSpace/asm-study/target/Person.class")) {
//                        fos.write(writer.toByteArray());
//
//                    }catch (IOException e) {
//                        e.printStackTrace();
//                    }

                    return writer.toByteArray();
                }
                return classfileBuffer;
            }
        });
    }
}
